#!/bin/bash

#### Input
TARGET_DIR=$1
BRANCH_NAME=$2
GIT_REPO_URL=$3

#### Input check
if test -z $TARGET_DIR || test -z $BRANCH_NAME || test -z $GIT_REPO_URL
then
    echo Usage: sh $0 TARGET_DIR BRANCH_NAME GIT_REPO_URL
    exit 1
fi

LOCK_FILE=/tmp/${TARGET_DIR//\//\+}.lock

{
    flock -n 3
    [ $? -eq 1 ] && { echo fail; exit; }

    if [ ! -d "$TARGET_DIR" ];then
        mkdir -p $TARGET_DIR
        git clone $GIT_REPO_URL $TARGET_DIR
        git -C $TARGET_DIR checkout -f $BRANCH_NAME
        exit 0
    else
        OLD_VERSION=`git -C $TARGET_DIR rev-parse HEAD`
        git -C $TARGET_DIR pull origin $BRANCH_NAME
        git -C $TARGET_DIR checkout -f $BRANCH_NAME
        NEW_VERSION=`git -C $TARGET_DIR rev-parse HEAD`

        if [ "$OLD_VERSION" == "$NEW_VERSION" ]; then
            exit 1
        else
            exit 0
        fi
    fi

} 3<>$LOCK_FILE
